
import fs from "node:fs";
import { input, number, select } from '@inquirer/prompts';
import { 排盘 } from './bazi.js';

process.on('uncaughtException', (error) => {
  if (error instanceof Error && error.name === 'ExitPromptError') {
    console.log('👋 until next time!');
  } else {
    // Rethrow unknown errors
    throw error;
  }
});

async function main() {
  const 性别: "男" | "女" = await select({
    message: '请选择性别',
    choices: [
      { name: "男", value: "男" },
      { name: "女", value: "女" },
    ],
  });
  const 日期类型: "公历" | "农历" = await select({
    message: '请选择日期类型',
    choices: [
      { name: "公历", value: "公历" },
      { name: "农历", value: "农历" },
    ],
  });
  const 年 = await number({ required: true, message: '请输入出生年份' });
  const 月 = await select({
    message: '请选择出生月份',
    choices: Array.from({ length: 12 }, (_, i) => ({
      name: `${i + 1}月`,
      value: i + 1
    }))
  });
  const 日 = await number({ required: true, message: '请输入出生日' });
  let 时 = await input({ required: true, message: '请输入出生时' });
  let 分 = 0;
  let 秒 = 0;
  if (时.includes(':')) {
    const parts = 时.split(':').map(Number);
    时 = parts[0]!.toString();
    if (parts.length >= 2) {
      分 = parts[1]!;
    }
    if (parts.length === 3) {
      秒 = parts[2]!;
    }
  }

  const result = 排盘(
    性别,
    {
      类型: 日期类型,
      年: 年!,
      月: 月!,
      日: 日!,
      时: parseInt(时),
      分: 分,
      秒: 秒
    }
  );
  const { 文本, ...obj } = result;
  console.log(obj);
  console.log(文本);

  fs.writeFileSync('排盘结果.json', JSON.stringify(obj, null, 2), { encoding: 'utf-8' });
  fs.writeFileSync('排盘结果.txt', 文本, { encoding: 'utf-8' });
  console.log('结果已保存到 排盘结果.json 文件中');
  console.log('bye~');
}
main();
